// 页面动画效果管理
const PageAnimations = {
    // 页面加载动画
    pageLoad: {
        // 淡入效果
        fadeIn() {
            document.body.style.opacity = '0';
            document.body.style.transition = 'opacity 0.3s ease-in-out';
            
            window.addEventListener('DOMContentLoaded', () => {
                setTimeout(() => {
                    document.body.style.opacity = '1';
                }, 50);
            });
        },

        // 从下往上滑入
        slideUp() {
            const main = document.querySelector('main') || document.querySelector('.container-app');
            if (main) {
                main.style.opacity = '0';
                main.style.transform = 'translateY(20px)';
                main.style.transition = 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)';
                
                window.addEventListener('DOMContentLoaded', () => {
                    setTimeout(() => {
                        main.style.opacity = '1';
                        main.style.transform = 'translateY(0)';
                    }, 100);
                });
            }
        }
    },

    // 列表项动画
    listItems: {
        // 渐进式显示列表项
        staggerFadeIn(selector = '.card-hover, .bg-white', delay = 50) {
            const items = document.querySelectorAll(selector);
            items.forEach((item, index) => {
                item.style.opacity = '0';
                item.style.transform = 'translateY(10px)';
                item.style.transition = 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)';
                
                setTimeout(() => {
                    item.style.opacity = '1';
                    item.style.transform = 'translateY(0)';
                }, index * delay);
            });
        },

        // 滚动触发动画
        scrollTrigger(selector = '.card-hover, .bg-white') {
            const observerOptions = {
                threshold: 0.1,
                rootMargin: '0px 0px -50px 0px'
            };
            
            const scrollObserver = new IntersectionObserver((entries) => {
                entries.forEach(entry => {
                    if (entry.isIntersecting) {
                        entry.target.style.opacity = '1';
                        entry.target.style.transform = 'translateY(0)';
                        // 添加一个类来标记已经动画过
                        entry.target.classList.add('animated');
                    }
                });
            }, observerOptions);
            
            document.querySelectorAll(selector).forEach(item => {
                if (!item.classList.contains('animated')) {
                    item.style.opacity = '0';
                    item.style.transform = 'translateY(20px)';
                    item.style.transition = 'all 0.5s cubic-bezier(0.4, 0, 0.2, 1)';
                    scrollObserver.observe(item);
                }
            });
        }
    },

    // 数据加载动画
    loading: {
        // 显示骨架屏
        showSkeleton(container, count = 3) {
            const skeletonHTML = `
                <div class="skeleton-item bg-white rounded-2xl p-4 mb-3 animate-pulse">
                    <div class="flex gap-3">
                        <div class="w-20 h-20 bg-gray-200 rounded-xl"></div>
                        <div class="flex-1">
                            <div class="h-4 bg-gray-200 rounded mb-2 w-3/4"></div>
                            <div class="h-3 bg-gray-200 rounded mb-2 w-full"></div>
                            <div class="h-3 bg-gray-200 rounded w-1/2"></div>
                        </div>
                    </div>
                </div>
            `;
            
            const skeletons = Array(count).fill(skeletonHTML).join('');
            if (typeof container === 'string') {
                const element = document.querySelector(container);
                if (element) element.innerHTML = skeletons;
            } else {
                container.innerHTML = skeletons;
            }
        },

        // 隐藏骨架屏并显示真实内容
        hideSkeleton(container, content) {
            const element = typeof container === 'string' ? document.querySelector(container) : container;
            if (!element) return;

            // 淡出骨架屏
            element.style.transition = 'opacity 0.3s ease-out';
            element.style.opacity = '0';
            
            setTimeout(() => {
                element.innerHTML = content;
                element.style.opacity = '1';
                // 触发新内容的动画
                PageAnimations.listItems.staggerFadeIn(`${typeof container === 'string' ? container : ''} > *`, 30);
            }, 300);
        },

        // 显示加载中提示
        showLoadingOverlay(message = '加载中...') {
            const overlay = document.createElement('div');
            overlay.id = 'loading-overlay';
            overlay.className = 'fixed inset-0 bg-black/30 backdrop-blur-sm z-50 flex items-center justify-center';
            overlay.innerHTML = `
                <div class="bg-white rounded-2xl px-8 py-6 shadow-xl flex items-center gap-3">
                    <div class="w-5 h-5 border-3 border-primary border-t-transparent rounded-full animate-spin"></div>
                    <span class="text-text-primary font-medium">${message}</span>
                </div>
            `;
            document.body.appendChild(overlay);
            
            // 淡入效果
            setTimeout(() => {
                overlay.style.opacity = '1';
            }, 10);
        },

        // 隐藏加载中提示
        hideLoadingOverlay() {
            const overlay = document.getElementById('loading-overlay');
            if (overlay) {
                overlay.style.transition = 'opacity 0.3s ease-out';
                overlay.style.opacity = '0';
                setTimeout(() => overlay.remove(), 300);
            }
        }
    },

    // 按钮点击效果
    button: {
        // 涟漪效果
        ripple(event, element) {
            const ripple = document.createElement('span');
            const rect = element.getBoundingClientRect();
            const size = Math.max(rect.width, rect.height);
            const x = event.clientX - rect.left - size / 2;
            const y = event.clientY - rect.top - size / 2;
            
            ripple.style.cssText = `
                position: absolute;
                width: ${size}px;
                height: ${size}px;
                left: ${x}px;
                top: ${y}px;
                border-radius: 50%;
                background: rgba(255, 255, 255, 0.5);
                transform: scale(0);
                animation: ripple-animation 0.6s ease-out;
                pointer-events: none;
            `;
            
            element.style.position = 'relative';
            element.style.overflow = 'hidden';
            element.appendChild(ripple);
            
            setTimeout(() => ripple.remove(), 600);
        },

        // 缩放效果
        scalePress(element) {
            element.addEventListener('mousedown', function() {
                this.style.transform = 'scale(0.95)';
            });
            element.addEventListener('mouseup', function() {
                this.style.transform = 'scale(1)';
            });
            element.addEventListener('mouseleave', function() {
                this.style.transform = 'scale(1)';
            });
            element.addEventListener('touchstart', function() {
                this.style.transform = 'scale(0.95)';
            });
            element.addEventListener('touchend', function() {
                this.style.transform = 'scale(1)';
            });
        }
    },

    // 页面切换动画
    pageTransition: {
        // 淡出当前页面并跳转
        fadeOut(url, delay = 300) {
            document.body.style.transition = 'opacity 0.3s ease-out';
            document.body.style.opacity = '0';
            
            setTimeout(() => {
                window.location.href = url;
            }, delay);
        },

        // 从右侧滑入
        slideFromRight() {
            const main = document.querySelector('main') || document.querySelector('.container-app');
            if (main) {
                main.style.opacity = '0';
                main.style.transform = 'translateX(20px)';
                main.style.transition = 'all 0.4s cubic-bezier(0.4, 0, 0.2, 1)';
                
                requestAnimationFrame(() => {
                    main.style.opacity = '1';
                    main.style.transform = 'translateX(0)';
                });
            }
        }
    },

    // 滚动动画
    scroll: {
        // 平滑滚动到顶部
        toTop(duration = 600) {
            const start = window.pageYOffset;
            const startTime = performance.now();
            
            function animation(currentTime) {
                const timeElapsed = currentTime - startTime;
                const progress = Math.min(timeElapsed / duration, 1);
                
                // 缓动函数
                const ease = progress < 0.5
                    ? 2 * progress * progress
                    : 1 - Math.pow(-2 * progress + 2, 2) / 2;
                
                window.scrollTo(0, start * (1 - ease));
                
                if (progress < 1) {
                    requestAnimationFrame(animation);
                }
            }
            
            requestAnimationFrame(animation);
        },

        // 平滑滚动到元素
        toElement(element, offset = 0, duration = 600) {
            const targetPosition = element.getBoundingClientRect().top + window.pageYOffset - offset;
            const startPosition = window.pageYOffset;
            const distance = targetPosition - startPosition;
            const startTime = performance.now();
            
            function animation(currentTime) {
                const timeElapsed = currentTime - startTime;
                const progress = Math.min(timeElapsed / duration, 1);
                
                // 缓动函数
                const ease = progress < 0.5
                    ? 2 * progress * progress
                    : 1 - Math.pow(-2 * progress + 2, 2) / 2;
                
                window.scrollTo(0, startPosition + distance * ease);
                
                if (progress < 1) {
                    requestAnimationFrame(animation);
                }
            }
            
            requestAnimationFrame(animation);
        }
    },

    // 数字滚动动画
    counter: {
        animate(element, start, end, duration = 1000) {
            const startTime = performance.now();
            const range = end - start;
            
            function update(currentTime) {
                const elapsed = currentTime - startTime;
                const progress = Math.min(elapsed / duration, 1);
                
                const current = Math.floor(start + range * progress);
                element.textContent = current.toLocaleString();
                
                if (progress < 1) {
                    requestAnimationFrame(update);
                }
            }
            
            requestAnimationFrame(update);
        }
    },

    // 初始化所有动画
    init(options = {}) {
        const defaults = {
            pageLoad: true,
            listItems: true,
            buttons: true,
            scrollTrigger: true
        };
        
        const config = { ...defaults, ...options };
        
        // 页面加载动画
        if (config.pageLoad) {
            this.pageLoad.fadeIn();
        }
        
        // 列表项动画
        if (config.listItems) {
            window.addEventListener('load', () => {
                setTimeout(() => {
                    this.listItems.staggerFadeIn('.card-hover, .bg-white', 50);
                }, 200);
            });
        }
        
        // 按钮效果
        if (config.buttons) {
            window.addEventListener('load', () => {
                document.querySelectorAll('button, .btn').forEach(btn => {
                    this.button.scalePress(btn);
                    btn.addEventListener('click', (e) => {
                        if (!btn.classList.contains('no-ripple')) {
                            this.button.ripple(e, btn);
                        }
                    });
                });
            });
        }
        
        // 滚动触发动画
        if (config.scrollTrigger) {
            window.addEventListener('load', () => {
                this.listItems.scrollTrigger('.card-hover, .bg-white');
            });
        }
        
        // 添加返回顶部按钮
        this.addBackToTop();
    },

    // 添加返回顶部按钮
    addBackToTop() {
        // 检查是否已存在
        if (document.getElementById('back-to-top')) return;
        
        const backToTop = document.createElement('button');
        backToTop.id = 'back-to-top';
        backToTop.className = 'fixed bottom-24 right-4 w-12 h-12 bg-primary text-white rounded-full shadow-xl opacity-0 transition-all duration-300 z-40 flex items-center justify-center hover:bg-primary-dark';
        backToTop.innerHTML = '<i class="fa fa-arrow-up"></i>';
        backToTop.style.pointerEvents = 'none';
        
        document.body.appendChild(backToTop);
        
        // 滚动显示/隐藏
        window.addEventListener('scroll', () => {
            if (window.pageYOffset > 300) {
                backToTop.style.opacity = '1';
                backToTop.style.pointerEvents = 'auto';
            } else {
                backToTop.style.opacity = '0';
                backToTop.style.pointerEvents = 'none';
            }
        });
        
        // 点击返回顶部
        backToTop.addEventListener('click', () => {
            this.scroll.toTop();
        });
    }
};

// 添加必要的CSS动画
const style = document.createElement('style');
style.textContent = `
    @keyframes ripple-animation {
        to {
            transform: scale(4);
            opacity: 0;
        }
    }
    
    @keyframes fadeIn {
        from {
            opacity: 0;
        }
        to {
            opacity: 1;
        }
    }
    
    @keyframes slideUp {
        from {
            transform: translateY(20px);
            opacity: 0;
        }
        to {
            transform: translateY(0);
            opacity: 1;
        }
    }
    
    @keyframes pulse {
        0%, 100% {
            opacity: 1;
        }
        50% {
            opacity: 0.5;
        }
    }
    
    .animate-pulse {
        animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite;
    }
    
    .animate-spin {
        animation: spin 1s linear infinite;
    }
    
    @keyframes spin {
        from {
            transform: rotate(0deg);
        }
        to {
            transform: rotate(360deg);
        }
    }
    
    /* 页面切换动画 */
    .page-enter {
        animation: fadeIn 0.3s ease-in-out;
    }
    
    .page-exit {
        animation: fadeOut 0.3s ease-in-out;
    }
    
    @keyframes fadeOut {
        from {
            opacity: 1;
        }
        to {
            opacity: 0;
        }
    }
    
    /* 平滑过渡 */
    * {
        -webkit-tap-highlight-color: transparent;
    }
    
    button, a, .card-hover {
        transition: all 0.2s ease-in-out;
    }
    
    /* 返回顶部按钮动画 */
    #back-to-top:hover {
        transform: translateY(-2px);
        box-shadow: 0 8px 24px rgba(16, 185, 129, 0.3);
    }
    
    #back-to-top:active {
        transform: translateY(0);
    }
`;
document.head.appendChild(style);

// 导出到全局
window.PageAnimations = PageAnimations;

// 自动初始化（如果需要禁用自动初始化，可以在引入前设置 window.DISABLE_AUTO_ANIMATE = true）
if (!window.DISABLE_AUTO_ANIMATE) {
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', () => {
            PageAnimations.init();
        });
    } else {
        PageAnimations.init();
    }
}

